﻿CREATE PROCEDURE [ServiceEngine].[CreateSchema]
	@Name nvarchar(400),
	@Description ntext = null,
	@ID uniqueidentifier OUTPUT
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	SET NOCOUNT ON;

	SELECT @ID = EntityID FROM ServiceEngine.Names WHERE EntityName = @Name AND EntityTypeID = 9

	BEGIN TRY
		IF (@ID IS NULL)
		BEGIN
			SET @ID = NewID()
			
			BEGIN TRANSACTION
			INSERT INTO ServiceEngine.Schemas (SchemaID)
			VALUES (@ID)

			BEGIN TRY
				INSERT INTO ServiceEngine.Names (EntityID, EntityTypeID, EntityName, EntityDescription)
				VALUES (@ID, 9, @Name, @Description)
			END TRY
			BEGIN CATCH

				SELECT 
					@ErrorMessage = 'Attempt to insert Schema with duplicate namespace uri failed',
					@ErrorSeverity = 11,
					@ErrorState = ERROR_STATE();

				RAISERROR (@ErrorMessage, 
						   @ErrorSeverity,
						   1);
			END CATCH

			COMMIT TRANSACTION
		END
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
END


